package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"rbac/cache"
	"rbac/models"
	"rbac/pkg"
	"strconv"
	"time"
)

type UserController struct {
	beego.Controller
}

type Res struct {
	Code int         `json:"code"`
	Res  string      `json:"res"`
	Data interface{} `json:"data"`
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "用户名或密码为空",
		}
		c.ServeJSON()
		return
	}
	login := "login_key" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, login).Int()
	if errCount >= 3 {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "密码错误3次,禁止登录",
		}
		c.ServeJSON()
		return
	}
	var err error
	var user models.User
	err = models.DB.Model(&models.User{}).Where("username = ?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "用户查询失败",
		}
		c.ServeJSON()
		return
	}
	if user.ID == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "用户不存在",
		}
		c.ServeJSON()
		return
	}

	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, login)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, login, 3, time.Hour*2)
			c.Data["json"] = Res{
				Code: 0,
				Res:  "用户密码错误3次，封禁2小时",
			}
			c.ServeJSON()
			return
		}

		c.Data["json"] = Res{
			Code: 0,
			Res:  "密码错误",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Res:  "登陆成功",
		Data: user,
	}
	c.ServeJSON()
}
func (c *UserController) RoleNodeAdd() {
	rid, _ := c.GetInt("rid", 0)
	nid, _ := c.GetInt("nid", 0)
	if rid == 0 || nid == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "字段为空，添加失败",
		}
		c.ServeJSON()
		return
	}
	var data = models.RoleNodeRelation{
		Rid: rid,
		Nid: nid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "添加失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Res:  "添加成功",
	}
	c.ServeJSON()
}
func (c *UserController) UserRoleList() {
	uid, _ := c.GetInt("uid", 0)
	if uid == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "用户不存在",
		}
		c.ServeJSON()
		return
	}
	var Role []models.Role
	err := models.DB.Model(&models.Role{}).
		Joins("left join user_role_relations on user_role_relations.rid = roles.id").
		Where("user_role_relations.rid = ?", uid).
		Find(&Role).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Res:  "查询成功",
			Data: Role,
		}
		c.ServeJSON()

	}

}
func (c *UserController) RoleNode() {
	rid, _ := c.GetInt("rid", 0)
	if rid == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "角色不存在",
		}
		c.ServeJSON()
		return
	}
	var Node []models.Node
	err := models.DB.Model(&models.Node{}).
		Joins("left join role_node_relations on role_node_relations.nid = nodes.id").
		Where("role_node_relations.rid = ?", rid).
		Find(&Node).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Res:  "查询成功",
			Data: Node,
		}
		c.ServeJSON()

	}
}
func (c *UserController) RoleAdd() {
	role_name := c.GetString("role_name")
	if role_name == "" {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "角色名为空",
		}
		c.ServeJSON()
		return
	}
	var data = models.Role{
		RoleName: role_name,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "添加失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Res:  "添加成功",
		}
		c.ServeJSON()
	}

}
func (c *UserController) PageList() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)

	offset := (page - 1) * size

	query := models.DB.Model(&models.User{})

	var count int64
	query.Count(&count)

	var post []models.User
	err := query.Offset(offset).Limit(size).Find(&post).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "查询失败",
		}
		c.ServeJSON()
		return
	} else {
		PageData := make(map[string]interface{})
		PageData["count"] = count
		PageData["post"] = post
		c.Data["json"] = Res{
			Code: 200,
			Res:  "查询成功",
			Data: PageData,
		}
		c.ServeJSON()
	}
}
func (c *UserController) UserAdd() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "用户名或密码为空",
		}
		c.ServeJSON()
		return
	}
	var data = models.User{
		Username: username,
		Password: pkg.Md5Str(password),
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "添加失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Res:  "添加成功",
		}
		c.ServeJSON()
	}
}

func (c *UserController) UserList() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	offset := (page - 1) * size
	var err error
	var user []models.User
	query := models.DB.Model(&models.User{})
	var count int64
	query.Count(&count)

	listKey := "list_key"
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, listKey).Result()
	if cacheJson == "" {
		query.Limit(size).Offset(offset).Find(&user)
		dataJson, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, listKey, dataJson, time.Hour*2)
	} else {
		err = json.Unmarshal([]byte(cacheJson), &user)
		if err != nil {
			c.Data["json"] = Res{
				Code: 0,
				Res:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
	}
	c.Data["json"] = Res{
		Code: 200,
		Res:  "查询成功",
		Data: user,
	}
	c.ServeJSON()
}
func (c *UserController) Del() {
	id, _ := c.GetInt("id")
	if id == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "用户不存在",
		}
		c.ServeJSON()
		return
	}
	err := models.DB.Delete(&models.User{}, id).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "删除失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Res:  "删除成功",
		}
		c.ServeJSON()

	}

}
func (c *UserController) UserDetail() {
	id, _ := c.GetInt("id")

	if id == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Res:  "用户id为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	dataList := "data_key" + strconv.Itoa(id)
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, dataList).Result()
	var user models.User
	if cacheJson == "" {
		models.DB.Model(&models.User{}).Where("id = ?", id).First(&user)
		dataJson, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, dataList, dataJson, time.Hour*2)
	} else {
		err := json.Unmarshal([]byte(cacheJson), &user)
		if err != nil {
			c.Data["json"] = Res{
				Code: 0,
				Res:  "缓存数据查询失败",
			}
			c.ServeJSON()
			return
		} else {
			c.Data["json"] = Res{
				Code: 200,
				Res:  "缓存数据查询成功",
				Data: user,
			}
			c.ServeJSON()

		}
	}

}
